package com.uatair.common.mqtt.util;

import com.google.common.collect.Lists;
import com.uatair.common.utils.StringUtils;
import org.apache.tomcat.util.codec.binary.Base64;
import org.jetbrains.annotations.NotNull;
import org.json.JSONObject;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.SecureRandom;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.X509EncodedKeySpec;
import java.util.ArrayList;
import java.util.List;

public class AESUtil {

    public static String AESEncode(String jsonStr, String KEY) {
        try {
            // 1.构造密钥生成器，指定为AES算法,不区分大小写
            KeyGenerator keygen = KeyGenerator.getInstance("AES");
            // 2.根据ecnodeRules规则初始化密钥生成器
            // 生成一个128位的随机源,根据传入的字节数组
            SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
            secureRandom.setSeed(KEY.getBytes());
            keygen.init(128, secureRandom);
            // 3.产生原始对称密钥
            SecretKey original_key = keygen.generateKey();
            // 4.获得原始对称密钥的字节数组
            byte[] raw = original_key.getEncoded();
            // 5.根据字节数组生成AES密钥
            SecretKey key = new SecretKeySpec(raw, "AES");
            // 6.根据指定算法AES自成密码器
            Cipher cipher = Cipher.getInstance("AES");
            // 7.初始化密码器，第一个参数为加密(Encrypt_mode)或者解密解密(Decrypt_mode)操作，第二个参数为使用的KEY
            cipher.init(Cipher.ENCRYPT_MODE, key);
            // 8.获取加密内容的字节数组(这里要设置为utf-8)不然内容中如果有中文和英文混合中文就会解密为乱码
            byte[] byte_encode = jsonStr.getBytes(StandardCharsets.UTF_8);
            // 9.根据密码器的初始化方式--加密：将数据加密
            byte[] byte_AES = cipher.doFinal(byte_encode);
            // 10.将加密后的数据转换为字符串
            String AES_encode = new String(new Base64().encode(byte_AES));
            // 11.将字符串返回
            return AES_encode;
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 如果有错就返加nulll
        return null;
    }

    public static String AESDecode(String content, String KEY) {
        try {
            // 1.构造密钥生成器，指定为AES算法,不区分大小写
            KeyGenerator keygen = KeyGenerator.getInstance("AES");
            // 2.根据ecnodeRules规则初始化密钥生成器
            // 生成一个128位的随机源,根据传入的字节数组
            SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
            secureRandom.setSeed(KEY.getBytes());
            keygen.init(128, secureRandom);
            // 3.产生原始对称密钥
            SecretKey original_key = keygen.generateKey();
            // 4.获得原始对称密钥的字节数组
            byte[] raw = original_key.getEncoded();
            // 5.根据字节数组生成AES密钥
            SecretKey key = new SecretKeySpec(raw, "AES");
            // 6.根据指定算法AES自成密码器
            Cipher cipher = Cipher.getInstance("AES");
            // 7.初始化密码器，第一个参数为加密(Encrypt_mode)或者解密(Decrypt_mode)操作，第二个参数为使用的KEY
            cipher.init(Cipher.DECRYPT_MODE, key);
            // 8.将加密并编码后的内容解码成字节数组
            byte[] byte_content = new Base64().decode(content);
            //解密
            byte[] byte_decode = cipher.doFinal(byte_content);
            String AES_decode = new String(byte_decode, StandardCharsets.UTF_8);
            return AES_decode;
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 如果有错就返加nulll
        return null;
    }


    @NotNull
    public static List<JSONObject> getJsonObjects(List<String> strings) {
        List<String> traces = new ArrayList<>();
        for (String string : strings) {
            if(StringUtils.isNotEmpty(string)) {
                byte[] decodedData = org.apache.commons.codec.binary.Base64.decodeBase64(string);
                byte[] decrypted = UAesUtil.uaDecrypt(decodedData);
                String jsonData = new String(decrypted, StandardCharsets.UTF_8);
                traces.add(jsonData);
            }
        }
        int size = 1;
        if (traces.size() > 500)
            size = 5;
        if (traces.size() > 1000)
            size = 10;
        List<List<String>> batches = Lists.partition(traces, size);
        List<JSONObject> traceJson = new ArrayList<>();
        for (List<String> trace : batches) {
            JSONObject jsonObject = new JSONObject(trace.get(0));
            traceJson.add(jsonObject);
        }
        return traceJson;
    }

    /**
     * RSA公钥加密方法
     */
    public static String rsaEncrypt(String str, String publicKey) throws Exception {
        byte[] decoded = java.util.Base64.getDecoder().decode(publicKey);
        RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA")
                .generatePublic(new X509EncodedKeySpec(decoded));

        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, pubKey);
        return java.util.Base64.getEncoder().encodeToString(cipher.doFinal(str.getBytes(StandardCharsets.UTF_8)));
    }

    public static String formatOrderId(String originalOrderId) {
        if (StringUtils.isBlank(originalOrderId)) {
            throw new IllegalArgumentException("OrderID不能为空");
        }
        // 分割原始ID
        String[] parts = originalOrderId.split("-");
        if (parts.length < 3) {
            throw new IllegalArgumentException("无效的OrderID格式");
        }
        // 提取产品序号部分(保留原始格式)
        String productSerial = parts[1];
        // 提取日期部分
        String datePart = parts[2];
        // 处理随机数部分(补0到8位)
        String randomNumber = parts[3];
        String paddedRandom = String.format("%08d", Integer.parseInt(randomNumber));
        return String.format("%s-%s-%s", productSerial, datePart, paddedRandom);
    }

    public static void main(String[] args) {
        String s = formatOrderId("TA-Q20Y672239043273-20250805-1");
        System.out.println(s);
    }
}
